#     TextLocutor
#     Copyright (C) 2009  Jose Ignacio Naranjo Hernandez (joseignacio.naranjo@gmail.com)

#     This program is free software: you can redistribute it and/or modify
#     it under the terms of the GNU Affero General Public License as
#     published by the Free Software Foundation, either version 3 of the
#     License, or (at your option) any later version.

#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU Affero General Public License for more details.

#     You should have received a copy of the GNU Affero General Public License
#     along with this program.  If not, see <http://www.gnu.org/licenses/>.

import time
from httplib import BadStatusLine
import urllib
import urllib2
import logging
import sys
import os
import threading

from BeautifulSoup import BeautifulSoup
from AEConnector import AEConnector

_FOOTBALL_EVENT = '/football_scores/event/'

_URL_LIVE_SCORES = 'http://www.xscores.com/LiveScore.do?state=promptSoccerScoreLine&sport=1'


def remove_repetitions(list):
    """ Remove the repeated values inside a list """
    list_aux = []
    while (list != []):
        element = list.pop()
        if element not in list:
            list_aux.append(element)
    return list_aux


class Carrusel(object):
                
    def __init__(self, connector):
        self.url = connector.url_base + _FOOTBALL_EVENT
        self.connector = connector
         
    def run(self):
        last_match = {}
        last_match_aux = {}
        while (True):
            try:
                page = urllib.urlopen(_URL_LIVE_SCORES)
            except IOError:
                logging.info("Problems retrieving the page")
                time.sleep(180)
                continue

            soup = BeautifulSoup(page.read())
            try:
                soup_results = soup.findAll(name='tbody', attrs={'id': 'scoreTable'})[0].findAll('tr')
            except IndexError:
                logging.info("Problems retrieving the page")
                time.sleep(180)
                continue
            
            first = True
            for result in soup_results:
                items = result.findAll('td')
                try:
                    match = {'country': result.findAll('img')[0]['title'],
                             'division': items[2].string,
                             'home': ' '.join([n.capitalize() for n in items[3].string.split(' ')]),
                             'visitor': ' '.join([n.capitalize() for n in items[4].string.split(' ')]),
                             'score': items[5].string,
                             'latest_scorer': items[6].string}
                
                    if last_match == {}:
                        last_match = match
                        last_match_aux = match
                        break
                    
                    else:
                        if last_match == match:
                            break
                        else:
                            if first == True:
                                last_match_aux = match
                                first = False
                            
                            try:
                                if match['latest_scorer'] is None:
                                    message = '%s-%s : %s : %s' % (match['home'],
                                                                   match['visitor'],
                                                                   '',
                                                                   match['score'])
                                    values = {'home': match['home'],
                                              'visitor': match['visitor'],
                                              'scorer': '',
                                              'score': match['score']}
                                else:
                                    message = '%s-%s : %s : %s' % (match['home'],
                                                                   match['visitor'],
                                                                   match['latest_scorer'],
                                                                   match['score'])
                                    values = {'home': match['home'],
                                              'visitor': match['visitor'],
                                              'scorer': match['latest_scorer'],
                                              'score': match['score']}

                                logging.info(message)

                                data = urllib.urlencode(values)
                                # TODO: Exception
                                if match['score'] == '1 HF': # the match starts
                                    try:
                                        self.connector.sendRequest(self.url, data)
                                    except urllib2.HTTPError, e:
                                        logging.error("%s: The match couldn't be 'started' because of a server exception: %s" % (message, e))
                                elif match['score'] == '2 HF': # no event
                                    pass
                                elif match['score'] == 'H/T': # no event
                                    pass
                                elif match['score'] == 'E/T': # no event
                                    pass
                                elif match['score'] == 'Post': # no event
                                    pass
                                elif match['score'] == 'Sched': # no event?
                                    pass
                                else:
                                    users = self.getUsers(data)
                                    if (users != None):
                                        self.courierBurst(remove_repetitions(users.split('&')), data)
                            except BadStatusLine, e:
                                logging.critical(e)
                except IndexError, e:
                    logging.critical(result)
                            
            time.sleep(20)
            last_match = last_match_aux
            
    def getUsers(self, message):
        # When a goal is scored, this method notifies it and receives a list
        # of users that belong to the event.
        tries = 3
        users = None
        while (tries>0):
            # The while is for preventing errors. Where there is some kind of internal
            # sever error, try again. Just 3 attemps.
            try:
                users_f = self.connector.sendRequest(self.url, message)
                users = users_f.read()
                if users == '':
                    users = None
                break
            except urllib2.HTTPError, e:
                logging.error("%s: The users couldn't be gathered because of a server exception: %s" % (message, e))
                if tries == 0:
                    logging.error("No more tries")
                    break
            tries = tries - 1
        return users

    def courierBurst(self, users, message):
        logging.info(users)
        for u in users:
            thread = Courier(u, message, self.connector, self.url)
            thread.start()


class Courier(threading.Thread):
    
    def __init__(self, user, message, connector, url):
        threading.Thread.__init__(self)
        self.user = user
        self.message = message
        self.connector = connector
        self.url = url

    def run(self):
        tries = 3
        while (tries>0):
            # The while is for preventing errors. Where there is some kind of internal
            # sever error, try again. Just 3 attemps.
            try:
                response = self.connector.sendRequest(self.url, self.message + '&user=%s' % self.user)
                break
            except urllib2.HTTPError, e:
                logging.error("Error in a Courier: %s: %s" % (self.user, e))
                if tries == 0:
                    logging.error("No more tries")
                    break
            tries = tries - 1
        

def main(argv):
    logging.basicConfig(format=("%(asctime)s %(levelname)s %(filename)s:"
                                "%(lineno)s %(message)s "))
    logging.getLogger().setLevel(logging.DEBUG)
    
    try:
        connector = AEConnector(app_name='textlocutor', dev_server=True)
        Carrusel(connector).run()
    except KeyboardInterrupt:
        sys.exit(1)
    

if __name__ == "__main__":
  main(sys.argv)
